<?php
/**
 * Created by JetBrains PhpStorm.
 * User: taoqili
 * Date: 12-7-18
 * Time: 上午11: 32
 * UEditor编辑器通用上传类
 */
class Uploader
{
    private $fileField;            //文件域名
    private $file;                 //文件上传对象
    private $config;               //配置信息
    private $oriName;              //原始文件名
    private $fileName;             //新文件名
    private $fullName;             //完整文件名,即从当前配置目录开始的URL
    private $fileSize;             //文件大小
    private $fileType;             //文件类型
    private $stateInfo;            //上传状态信息,
    private $stateMap = array(    //上传状态映射表，国际化用户需考虑此处数据的国际化
        "SUCCESS" ,                //上传成功标记，在UEditor中内不可改变，否则flash判断会出错
        "文件大小超出 upload_max_filesize 限制" ,
        "文件大小超出 MAX_FILE_SIZE 限制" ,
        "文件未被完整上传" ,
        "没有文件被上传" ,
        "上传文件为空" ,
        "POST" => "文件大小超出 post_max_size 限制" ,
        "SIZE" => "文件大小超出网站限制" ,
        "TYPE" => "不允许的文件类型" ,
        "DIR" => "目录创建失败" ,
        "IO" => "输入输出错误" ,
        "UNKNOWN" => "未知错误" ,
        "MOVE" => "文件保存时出错"
    );

    /**
     * 构造函数
     * @param string $fileField 表单名称
     * @param array $config  配置项
     * @param bool $base64  是否解析base64编码，可省略。若开启，则$fileField代表的是base64编码的字符串表单名
     */
    public function __construct( $fileField , $config , $base64 = false )
    {
        $this->fileField = $fileField;
        $this->config = $config;
        $this->stateInfo = $this->stateMap[ 0 ];
        $this->upFile( $base64 );
    }

    /**
     * 上传文件的主处理方法
     * @param $base64
     * @return mixed
     */
    private function upFile( $base64 )
    {
        //处理base64上传
        if ( "base64" == $base64 ) {
            $content = $_POST[ $this->fileField ];
            $this->base64ToImage( $content );
            return;
        }

        //处理普通上传
        $file = $this->file = $_FILES[ $this->fileField ];
        if ( !$file ) {
            $this->stateInfo = $this->getStateInfo( 'POST' );
            return;
        }
        if ( $this->file[ 'error' ] ) {
            $this->stateInfo = $this->getStateInfo( $file[ 'error' ] );
            return;
        }
        if ( !is_uploaded_file( $file[ 'tmp_name' ] ) ) {
            $this->stateInfo = $this->getStateInfo( "UNKNOWN" );
            return;
        }

        $this->oriName = $file[ 'name' ];
        $this->fileSize = $file[ 'size' ];
        $this->fileType = $this->getFileExt();

        if ( !$this->checkSize() ) {
            $this->stateInfo = $this->getStateInfo( "SIZE" );
            return;
        }
        if ( !$this->checkType() ) {
            $this->stateInfo = $this->getStateInfo( "TYPE" );
            return;
        }
        $this->fullName = $this->getFolder('handle') . '/' . $this->getName();
        if ( $this->stateInfo == $this->stateMap[ 0 ] ) {
            if ( !move_uploaded_file( $file[ "tmp_name" ] , $this->fullName ) ) {
                $this->stateInfo = $this->getStateInfo( "MOVE" );
            }
        }
		
		//保存原图    20131107
        $original_Name = $this->getFolder('original') . '/' . $this->getName();
		@copy($this->fullName, $original_Name);
		
		//加水印    20131107
		if( $this->config['set_watermark'] == true ){
			$this->set_watermark("../watermark.png");
			$this->create_watermark($this->fullName);
		}
    }

	//图片水印设置，如果不生成添加水印则不用设置
    //$file : 水印图片 , $pos : 水印位置 , $trans : 水印透明度 
    private function set_watermark ($file, $pos = 6, $trans = 80) {      
        $this->watermark_file  = $file;
        $this->watermark_pos   = $pos;
        $this->watermark_trans = $trans;
    }
	
	//为图片添加水印      
    //$file : 要添加水印的文件      
    private function create_watermark ($file) {      
     
        //文件不存在则返回      
        if (!file_exists($this->watermark_file) || !file_exists($file)) return;      
        if (!function_exists('getImageSize')) return;      
              
        //检查GD支持的文件类型      
        $gd_allow_types = array();      
        if (function_exists('ImageCreateFromGIF')) $gd_allow_types['image/gif'] = 'ImageCreateFromGIF';      
        if (function_exists('ImageCreateFromPNG')) $gd_allow_types['image/png'] = 'ImageCreateFromPNG';      
        if (function_exists('ImageCreateFromJPEG')) $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';      
     
        //获取文件信息      
        $fileinfo = getImageSize($file);      
        $wminfo   = getImageSize($this->watermark_file);      
     
        if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;      
     
        if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {      
            if (array_key_exists($wminfo['mime'],$gd_allow_types)) {      
                      
                //从文件创建图像      
                $temp = $gd_allow_types[$fileinfo['mime']]($file);      
                $temp_wm = $gd_allow_types[$wminfo['mime']]($this->watermark_file);      
     
                //水印位置      
                switch ($this->watermark_pos) {                   
                    case 1 :  //顶部居左      
                        $dst_x = 0; $dst_y = 0; break;                    
                    case 2 : //顶部居中      
                        $dst_x = ($fileinfo[0] - $wminfo[0])/2; $dst_y = 0; break;                      
                    case 3 :  //顶部居右      
                        $dst_x = $fileinfo[0]; $dst_y = 0; break;                     
                    case 4 :  //底部居左      
                        $dst_x = 0; $dst_y = $fileinfo[1]; break;                     
                    case 5 :  //底部居中      
                        $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;           
                    case 6 :  //底部居右      
                        $dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break;      
                    default : //随机      
                        $dst_x = mt_rand(0,$fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$fileinfo[1]-$wminfo[1]);      
                }      
     
                if (function_exists('ImageAlphaBlending')) ImageAlphaBlending($temp_wm,false); //设定图像的混色模式      
                if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //保存完整的 alpha 通道信息      
     
                //为图像添加水印
                ImageCopy($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1]);
     
                //保存图片      
                switch ($fileinfo['mime']) {      
                    case 'image/jpeg' :      
                        @imageJPEG($temp,$file);      
                        break;      
                    case 'image/png' :      
                        @imagePNG($temp,$file);      
                        break;      
                    case 'image/gif' :       
                        @imageGIF($temp,$file);      
                        break;      
                }
                //销毁零时图像      
                @imageDestroy($temp);
                @imageDestroy($temp_wm);
            }      
        }      
    }
	
    /**
     * 处理base64编码的图片上传
     * @param $base64Data
     * @return mixed
     */
    private function base64ToImage( $base64Data )
    {
        $img = base64_decode( $base64Data );
        $this->fileName = time() . rand( 1 , 10000 ) . ".png";
        $this->fullName = $this->getFolder('handle') . '/' . $this->fileName;
        if ( !file_put_contents( $this->fullName , $img ) ) {
            $this->stateInfo = $this->getStateInfo( "IO" );
            return;
        }
        $this->oriName = "";
        $this->fileSize = strlen( $img );
        $this->fileType = ".png";
    }

    /**
     * 获取当前上传成功文件的各项信息
     * @return array
     */
    public function getFileInfo()
    {
        return array(
            "originalName" => $this->oriName ,
            "name" => $this->fileName ,
            "url" => $this->fullName ,
            "size" => $this->fileSize ,
            "type" => $this->fileType ,
            "state" => $this->stateInfo
        );
    }

    /**
     * 上传错误检查
     * @param $errCode
     * @return string
     */
    private function getStateInfo( $errCode )
    {
        return !$this->stateMap[ $errCode ] ? $this->stateMap[ "UNKNOWN" ] : $this->stateMap[ $errCode ];
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getName()
    {
        return $this->fileName = time() . rand( 1 , 10000 ) . $this->getFileExt();
    }

    /**
     * 文件类型检测
     * @return bool
     */
    private function checkType()
    {
        return in_array( $this->getFileExt() , $this->config[ "allowFiles" ] );
    }

    /**
     * 文件大小检测
     * @return bool
     */
    private function  checkSize()
    {
        return $this->fileSize <= ( $this->config[ "maxSize" ] * 1024 );
    }

    /**
     * 获取文件扩展名
     * @return string
     */
    private function getFileExt()
    {
        return strtolower( strrchr( $this->file[ "name" ] , '.' ) );
    }

    /**
     * 按照日期自动创建存储文件夹
     * @return string
     */
    private function getFolder($type)
    {
        $pathStr = $this->config[ "savePath" ].$type;
        if ( strrchr( $pathStr , "/" ) != "/" ) {
            $pathStr .= "/";
        }
        $pathStr .= date( "Ymd" );
        if ( !file_exists( $pathStr ) ) {
            if ( !mkdir( $pathStr , 0777 , true ) ) {
                return false;
            }
        }
        return $pathStr;
    }
}